package servlet;

import entity.Message;
import entity.Passage;
import service.CommonService;
import service.MessageService;
import service.PassageService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "MessageServlet")
public class MessageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用到的services
        CommonService commonService = new CommonService();
        PassageService passageService = new PassageService();
        MessageService messageService = new MessageService();

        //获取课程名称
        String courseName = commonService.getCourseName();
        request.setAttribute("courseName", courseName);

        //获取底部信息
        Passage bottomPassage = passageService.getPassageByField("5");
        String bottom_content = (bottomPassage == null) ? "暂无" : bottomPassage.getContent();
        request.setAttribute("bottom_content", bottom_content);

        //获取留言信息
        int page = Integer.valueOf(request.getParameter("page"));
        request.setAttribute("page",page);
        //获取留言总数用于分页
        int sum = messageService.getNumberOfMessages(2);
        int num_every_page = 10;
        int last_page = (int) Math.ceil((double)sum / num_every_page);
        if(sum == 0)
            last_page = 1;
        request.setAttribute("last_page", last_page);
        List<Message> messages = messageService.getMessageList(page);
        request.setAttribute("messages", messages);

        request.getRequestDispatcher("message.jsp").forward(request, response);
    }
}
